package AssetType

import (
	"ToolLibray/jwtx"
	"context"
	"property_api/utils/result"
	"property_api/utils/tree"
	"property_service/property_service"

	"github.com/zeromicro/go-zero/core/logx"
	"property_api/internal/svc"
	"property_api/internal/types"
)

type (
	PagesLogic struct {
		logx.Logger
		ctx    context.Context
		svcCtx *svc.ServiceContext
	}
	dept struct {
		types.AssetType
		Children []tree.NodeWithChildren `json:"children"`
	}
)

func (d *dept) GetID() int64 {
	//TODO implement me
	return d.ID
}

func (d *dept) GetParentID() int64 {
	//TODO implement me
	return d.ParentID
}

func (d *dept) GetChildren() []tree.NodeWithChildren {
	//TODO implement me
	return d.Children
}

func (d *dept) SetChildren(children []tree.NodeWithChildren) {
	d.Children = children
}

func NewPagesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PagesLogic {
	return &PagesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// Pages 查询资产类型的分页逻辑
func (l *PagesLogic) Pages(req *types.AssetTypePageReq) (resp *types.PageRes, err error) {
	// 设置租户ID，从上下文中获取
	tenantID := jwtx.GetUserTenantId64(l.ctx)

	// 设置创建用户和更新用户，从上下文中获取
	//userIdStr := xform.Int64ToString(jwtx.GetUserId(l.ctx))

	// 构建查询条件对象
	where := &property_service.AssetType{
		TenantID:           tenantID,               // 租户ID
		ID:                 req.ID,                 // 记录ID
		ParentID:           req.ParentID,           //父级编码（直接上级分类编号）
		ParentCode:         req.ParentCode,         //父级编码
		Remark:             req.Remark,             //备注
		ParentLs:           req.ParentLs,           //父级列表（格式：,A001,B002,C003,）
		PinyinCode:         req.PinyinCode,         //拼音简码
		Name:               req.Name,               // 资产类型名称
		Code:               req.Code,               //资产类型编码
		DepreciationPeriod: req.DepreciationPeriod, //资产折旧年限
	}

	// 调用服务层方法，查询资产类型记录的分页数据
	// 服务层方法 PropertyTypePage 会处理实际的数据库查询操作
	data, err := l.svcCtx.BasicService.AssetTypePage(l.ctx, &property_service.AssetTypePageReq{
		Page:  req.Page,  // 当前 页码
		Limit: req.Limit, // 每页条数
		Where: where,     // 查询条件
	})
	if req.Tree != 1 {
		return result.SucPage(data, types.AssetType{}).PageEd()
	}

	// 返回分页数据的响应
	return result.SucPage(data, dept{}, func(value interface{}) interface{} {
		data := value.([]*dept)
		return tree.MakeTreeByID(func() []tree.NodeWithChildren {
			convertedNodes := make([]tree.NodeWithChildren, 0)
			for _, category := range data {
				convertedNodes = append(convertedNodes, category)
			}
			return convertedNodes
		}())
	}).PageEd()
}
